﻿

using System;
using System.Reflection;
using System.Xml;
namespace HBase {
    public class InitServer {
        public static void start() {
            System.Threading.Tasks.Task.Factory.StartNew(() => {
                init();
            });
        }
        private static void init() {
            String path = "Conf/bean.config";
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlElement root = doc.DocumentElement;
            XmlNodeList childNodes = root.ChildNodes;
            foreach( XmlNode node in childNodes ) {
                createNode(node);
            }
        }
        private static void createNode(XmlNode node) {
            if( node.Attributes == null ) {
                return;
            }
            var className = node.Attributes["className"];
            var info = node.Attributes["info"];
            String value = className.Value;
            try {
                String dllName = value.Substring(0 ,value.LastIndexOf("."));
                String dllPath = AppDomain.CurrentDomain.BaseDirectory + dllName + ".dll";
                Assembly ass = System.Reflection.Assembly.LoadFile(dllPath);//要绝对路径
                Type type = ass.GetType(value);//必须使用名称空间+类名称
                if( node.Name == "task" ) {


                    ZtTask task = ( ZtTask ) Activator.CreateInstance(type);

                    createAndBegin(task ,node);
                    if( info != null ) {
                        String v = info.Value;
                        if( !String.IsNullOrEmpty(v) ) {
                            task.stat.className = v;
                        }
                    }
                } else if( node.Name == "factray" ) {
                    ZtFactray obj = ( ZtFactray ) Activator.CreateInstance(type);
                    var p = node.Attributes["p"];
                    if( p != null ) {
                        obj.setParam(p.Value.ToString());
                    }
                    ZtTask task = obj.create();
                    if( task != null ) {
                        createAndBegin(task ,node);
                    }
                }
            } catch( Exception e ) {
                LoggerCommon.error(value + "创建异常" + e.Message ,e);
            }
        }
        static void createAndBegin(ZtTask task ,XmlNode node) {
            ZtTaskConnect ipTask = task as ZtTaskConnect;
            if( ipTask != null ) {
                var ip = node.Attributes["ip"];
                if( ip != null ) {
                    ipTask.ip = ip.Value.ToString();
                }
                var readPort = node.Attributes["port"];
                if( readPort != null ) {
                    ipTask.port = int.Parse(readPort.Value.ToString());
                }
            }
            TaskPool.add(task);

            TaskPool.start(task.GetType());
        }
    }
}
